<?php
class Feed extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		$this->load->model('blog_model');
		$this->load->model('user_model');
		$this->load->model('feed_model');
		$this->load->model('tag_model');
	}
	
	public function post(){
		$ptype = $this->input->post('type');
		$pcontent = $this->input->post('content');
		$ptitle = $this->input->post('title');
		$tags = $this->input->post('tags');
		$uid = $this->session->userdata('user_id');
		$bid = $this->session->userdata('blog_id');
		
		$pid = $this->feed_model->post(
				$uid,$bid,$ptitle,$pcontent,$ptype
			);
		$this->tag_model->add_tags($pid,explode(' ', $tags));
	}
	
	public function share(){
		$pid = $this->input->post('pid');
		$reason = $this->input->post('reason');
		$uid = $this->session->userdata('user_id');
		$bid = $this->input->post('bid');
		
		$pid = $this->feed_model->share(
				$uid,$bid,$pid,$reason
		);
		echo $pid;
	}
	
	public function delete(){
		$pid = $this->input->post('pid');
		$uid = $this->session->userdata('user_id');
		$post = $this->feed_model->get($pid); 
		if($post['author']==$uid){
			$this->feed_model->delete($pid);
		}
	}
	
	public function url_to_link(){
		$url = $this->input->get('url');
		if(!preg_match('/^http(s?):\/\/*/', $url))
			$url = 'http://'.$url;
		$content = '';
		
		
		if (preg_match('/^(http):.+\\..+/i', $url)==1) {
			try
			{
				@$content=file_get_contents($url);
				$mode="#<title>(.*)</title>#iUs";
				if(preg_match($mode,$content,$arr)){
					$title = $arr[0];
					$title = str_replace('<title>', ' ', $title);
					$title = str_replace('</title>', ' ', $title);
					echo '<a href= "'.$url.'" target = "_blank">'.$title.'</a>';
				} else {
					echo '<a href= "'.$url.'" target = "_blank" title = "">'.$url.'</a>';;
				}
			}
			catch(Exception $e)
			{
				echo -1;
			}
		} else {
			echo -1;
		}
	}
	
	public function upload_image(){
		$bid = $this->session->userdata('blog_id');
		
		if ($bid){
		
			$config['upload_path'] = './public/image/feed';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size'] = '500';
			$config['max_width']  = '1024';
			$config['max_height']  = '768';
			$config['encrypt_name']  = true;
			
			
			$this->load->library('upload', $config);
			
			if ( ! $this->upload->do_upload('image-up'))
			{
				$error = array('error' => $this->upload->display_errors('<i>', '</i>'));
				$feedback['state'] = -1;
				$feedback['message'] = $error['error']; 
				echo json_encode($feedback);
			}
			else
			{
				$data = $this->upload->data();
				$feedback['state'] = 1;
				$feedback['message'] = $data['file_name'];
				echo json_encode($feedback);
			}
		} else {
			$feedback['state'] = -1;
			$feedback['message'] = 'need sign in';
			echo json_encode($feedback);
		}
	}
	
}

?>